package admin

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"mydemo/models"
	"net/http"
	"time"
)

type UserController struct {
	BaseController
}

func (con UserController) Index(c *gin.Context) {
	//查询数据库
	//userList := []models.User{}
	//models.DB.Debug().Find(&userList)
	//c.JSON(http.StatusOK, userList)

	//查询年龄age大于20岁的用户
	users := []models.User{}
	models.DB.Where("age > 20").Find(&users)
	c.JSON(http.StatusOK, users)
	//c.String(200, "用户列表")
	//con.success(c)
}
func (con UserController) Add(c *gin.Context) {
	user := models.User{
		Username: "lisi gorm",
		Age:      22,
		Email:    "123@qq.com",
		AddTime:  int(time.Now().Unix()),
	}
	result := models.DB.Create(&user)
	fmt.Println(user)
	c.JSON(http.StatusOK, gin.H{"row": result.RowsAffected})
}
func (con UserController) Edit(c *gin.Context) {
	//查询id=6的数据
	user := models.User{Id: 6}
	models.DB.First(&user)
	fmt.Println(user)
	//更新数据 保存所有字段
	user.Username = "lisi-1"
	user.Email = "321@qq.com"
	models.DB.Save(&user)

	user2 := models.User{}
	models.DB.Model(&user2).Where("id = ?", 6).Update("username", "lisi-2")

	user3 := models.User{}
	models.DB.Where("id = ?", 6).Find(&user3)
	user3.Username = "haha"
	user3.Email = "123@qq.com"
	models.DB.Save(&user3)
	c.JSON(http.StatusOK, user2)
}
func (con UserController) Delete(c *gin.Context) {
	user := models.User{Id: 6}
	models.DB.Delete(&user)

	//user2:=models.User{}
	models.DB.Where("username = ?", "gorm").Delete(&models.User{})
	c.String(200, "用户列表-delete")
}
